/**
 *
 */
function Google(clientId, apiKey, immediateAuthCallback) {
	this.accessToken = null;
	this.clientId = clientId;
	this.apiKey = apiKey;
	this.profile = new Object();
	this.scopes = 	[
						"https://www.googleapis.com/auth/plus.me",
						"https://www.googleapis.com/auth/drive.readonly",
						"https://spreadsheets.google.com/feeds"
					];


	/*
	 * Private partial function for gauth login callback handling
	 */
	this.authResultChecker = function (callback) {
		myObject = this;
		return function(authResult) {
			if (authResult['status']['signed_in'] == true) {
				myObject.accessToken = authResult["access_token"];

				window.gapi.client.load("plus", "v1").then(
					function() {
						window.gapi.client.plus.people.get({
						  "userId": "me",
						  "access_token": myObject.accessToken
						}).then(
							function(resp) {
								googleProfile = resp.result;
								myObject.profile.displayName = resp.result.displayName;
								myObject.profile.imageUrl = resp.result.image.url;

							  	if ("undefined" != typeof callback) {
									callback(myObject, true);
								}
							}, 
							function (error) {
								if ("undefined" != typeof callback) {
									callback(myObject, true, error);
								}
							}
						);
					}
				);
			}
			else {
				myObject.accessToken = null;
				if ("undefined" != typeof callback) {
					callback(myObject, false, authResult['error']);
				}
				
			}
		};
	};

	/*
	 * A callback for the Google API client JS to call when API SDK load complete
	 */
	this.gapiLoaded = function () {
		window.gapi.client.setApiKey(apiKey);
		window.gapi.auth.authorize({
				"client_id": this.clientId, 
				"scope": this.scopes.join(" "), 
				"immediate": true
			}, 
			this.authResultChecker(immediateAuthCallback));
	};

	// CONSTRUCTOR
	gapi.load("auth", $.proxy(this.gapiLoaded, this));
};

/**
 *
 */
Google.prototype.auth = function (callback) {
	window.gapi.auth.authorize({
				"client_id": this.clientId, 
				"hd": "ustream.tv",
				"cookiepolicy" : "single_host_origin",
				"scope": this.scopes.join(" "), 
				"immediate": false
			}, 
			this.authResultChecker(callback));
}

/**
 *
 */
Google.prototype.getProfile = function () {
	return this.profile;
};

/**
 *
 */
Google.prototype.pickDocument = function (callback) {
	var myObject = this;
	gapi.load('picker', {
		'callback': function() {
			var picker = new google.picker.PickerBuilder()
					.addView(google.picker.ViewId.DOCUMENTS)
					.setOAuthToken(myObject.accessToken)
					.setDeveloperKey(myObject.apiKey)
	            	.setCallback(function (data) { 
	            		if ("undefined" != typeof callback && "picked" == data.action) {
	            			callback(data.docs[0].id);
	            		}
	            	 })
	            	.build();
	        picker.setVisible(true);		
		}

	});
};

Google.prototype.fetchVideoURL = function (slide, callback) {
	var myObject = this;
	
	var fileId = $(slide).attr("data-video-id");
	if (!fileId) return;

	window.gapi.client.drive.files.get({
			"fileId": fileId,
			"access_token": myObject.accessToken
		}).then(
			function(resp) {
				callback(slide, resp.result.downloadUrl);
			},
			function(error) {
				console.log("Error getting URL for file: "+fileId)
			}
		);
}
/**
 *
 */
Google.prototype.fetchSimpleDocument = function (fileId, callback) {
	var myObject = this;
	
	window.gapi.client.load("drive", "v2").then(function () {
		window.gapi.client.drive.files.get({
			"fileId": fileId,
			"access_token": myObject.accessToken
		}).then(
			function(resp) {
				
				var script = resp.mimetype == "application/vnd.google-apps.spreadsheet" ? "download.php" : "getsheet.php";
				$.get("http://sipocz.info/vidoq/" + script, 
					{
						"url": resp.result.downloadUrl,
						"token": myObject.accessToken,
						"id": fileId
					},
					function (data) {
					
						if ("undefined" != typeof callback) {
							callback(data);
						} else {
							console.log("Missing callback for Google.fetchDocument()");
						}
					}
				);
			},
			function(error) {
				$("#loginMessage p").html(error.result.error.code + " - " + error.result.error.message);
				$("#loginMessage span").css("visibility", "hidden");
				callback(false);
			}
		);
	});

}